let nums18:number[]=[2,2,2,2,2],target:number=8;
console.log(fourSum(nums18,target));

function fourSum(nums: number[], target: number): number[][] {
    let result:number[][]=[];
    nums.sort((a,b)=>a-b)//从小到大
    
    let i:number=0;
    while(i<nums.length-3){
        if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target)
            break;
        if(nums[i]+nums[nums.length-3]+nums[nums.length-2]+nums[nums.length-1]<target){
            i=movei(i,nums)
            continue;
        } 
        let j=i+1;
        while(j<nums.length-2){
            if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target)
                break;
            if(nums[i]+nums[j]+nums[nums.length-2]+nums[nums.length-1]<target)
                {
                    j=movej(j,nums)
                    continue;
                }
            let l=j+1,r=nums.length-1;
            while(l<r){
                if(nums[i]+nums[j]+nums[l]+nums[r]>target){
                    r=moveR18(r,nums)
                }else if(nums[i]+nums[j]+nums[l]+nums[r]<target){
                    l=moveL18(l,nums);
                }else{
                    result.push([nums[i],nums[j],nums[l],nums[r]])
                    r=moveR18(r,nums)
                    l=moveL18(l,nums);
                }
            }
            j=movej(j,nums)
        }
        i=movei(i,nums)
    }
    return result;
};
function moveR18(r:number,nums:number[]):number{
    if(r-1===0)
        return 0;
    while((nums[r]===nums[r-1])){
       r--; 
       if(r<=1)
        break
    }
    r--;
    return r;
}
function moveL18(l:number,nums:number[]):number{
    if(l+1===nums.length-1)
        return nums.length-1;
    while((nums[l]===nums[l+1])){
        l++;
        if(l>=nums.length-1)
            break;
    }
    l++;
    return l;
}
function movei(i:number,nums:number[]):number{
    while(i<nums.length-1){
        if(nums[i]===nums[i+1])
            i++;
        else break;
    }
    i++;
    return i;
}
function movej(j:number,nums:number[]):number{
    while(j<nums.length-2){
        if(nums[j]===nums[j+1])
            j++;
        else break;
    }
    j++;
    return j;
}